import json

from django.db.models import Count
from django.http import JsonResponse
# Create your views here.
from django.views.decorators.csrf import csrf_exempt

from baobaoxiong.check_phone import check_phone
from baobaoxiong.upload_down import upload_img, download
from baobaoxiong.yueling import fn, fx
from parents.models import Parents
from teachers.models import Teacher
from schoolmaster.models import *


# 老师首页
@csrf_exempt
def teacher_index_views(request):
    uphone = request.POST.get('uphone')  # 获取老师电话
    teachar = Teacher.objects.filter(uphone=uphone, isDelete=False).first()
    upload_img(str(teachar.teacherphoto))  # 上传图片到七牛云
    url = download(str(teachar.teacherphoto))
    students = teachar.students.all()
    if students:
        # 添加学生信息
        l_students = []
        for student in students:
            # 测评次数
            num = student.test_results.all().aggregate(count=Count('id'))
            birth = fn(student.birth)
            upload_img(str(student.photo))  # 上传图片到七牛云
            stu_url = download(str(student.photo))
            dic = {
                'sid': student.id,  # 学生id
                'stuphoto': stu_url,  # 学生头像
                'sname': student.uname,  # 学生姓名
                'age': "%s岁%s个月" % (str(birth[0]), str(birth[1])),  # 月龄
                'gender': student.gender,  # 性别
                'count': num['count']  # 测评次数
            }
            l_students.append(dic)
        dic1 = {
            'tid': teachar.id,  # 老师id
            'photo': url,  # 老师头像
            'tname': teachar.uname,  # 老师姓名
            'uphone': teachar.uphone,  # 老师电话
            'studata': l_students,  # 学生数据
        }
        return JsonResponse(dic1)
    else:
        dic1 = {
            'tid': teachar.id,  # 老师id
            'photo': url,  # 老师头像
            'tname': teachar.uname,  # 老师姓名
            'uphone': teachar.uphone,  # 老师电话
            'studata': [],
        }
        return JsonResponse(dic1)


# 关联老师页面
@csrf_exempt
def query_teacher_views(request):
    # 老师电话
    uphone = request.POST.get('uphone')
    teacher = Teacher.objects.filter(uphone=uphone, isDelete=False).first()
    school = teacher.school  # 获取园所对象
    teachers = school.teachers.all().filter(isDelete=False)
    lst = []
    for tea in teachers:
        dic = {
            'id': tea.id,  # 老师id
            'tname': tea.uname,  # 老师名字
            'checked': '',  # 判断是否关联了老师
        }
        lst.append(dic)
    dic1 = {
        'ids': lst,  # 老师信息
    }
    return JsonResponse(dic1)


# 确定添加学生
@csrf_exempt
def certainty_add_views(request):
    # 老师电话
    uphone = request.POST.get('uphone')
    teacher = Teacher.objects.filter(uphone=uphone, isDelete=False).first()
    school = teacher.school  # 获取园所对象

    uname = request.POST.get('uname')  # 姓名
    photo = request.FILES.get('file')  # 头像
    birth = request.POST.get('birth')  # 出生日期
    gender = request.POST.get('gender')  # 性别
    opentime = request.POST.get('opentime')  # 开学时间
    endtime = request.POST.get('endtime')  # 结束时间

    motherphone = request.POST.get('motherphone')  # 妈妈电话
    leap1 = 0
    if motherphone:
        if Parents.objects.filter(uphone=motherphone):
            return JsonResponse({'status': 'error', 'text': '妈妈电话已存在'})
        elif check_phone(motherphone) == 'fail':
            return JsonResponse({'status': 'failed', 'text': '妈妈电话错误'})
        leap1 = 1
    
    fatherphone = request.POST.get('fatherphone')  # 爸爸电话
    leap2 = 0
    if fatherphone:
        if Parents.objects.filter(uphone=fatherphone):
            return JsonResponse({'status': 'error', 'text': '爸爸电话已存在'})
        elif check_phone(fatherphone) == 'fail':
            return JsonResponse({'status': 'failed', 'text': '爸爸电话错误'})
        leap2 = 1
    
    grandpaphone = request.POST.get('grandpaphone')  # 爷爷电话

    leap = 0  # 标记电话是否为空
    if grandpaphone:
        if Parents.objects.filter(uphone=grandpaphone):
            return JsonResponse({'status': 'error', 'text': '爷爷电话已存在'})
        elif check_phone(grandpaphone) == 'fail':
            return JsonResponse({'status': 'failed', 'text': '爷爷电话错误'})
        leap = 1

    ids = request.POST.get('ids')  # 获取老师id
    id_lst = json.loads(ids)  # 解析json格式
    # 保存数据到学生表中
    student = Student()
    student.uname = uname
    student.photo = photo
    student.birth = birth
    student.gender = gender
    student.openschool = opentime
    student.endschool = endtime
    student.school_id = school.id  # 关联园所 id
    student.save()

    xuesheng = Student.objects.filter(uname=uname, birth=birth).first()
    # 关联老师
    for x in id_lst:
        teacher = Teacher.objects.get(id=int(x['id']))
        teacher.students.add(xuesheng.id)
    if leap1 == 1:
        user = Users.objects.filter(uphone=motherphone).first()  # 查询用户表是否有该电话
        role = Role.objects.get(id=1)
        if user:
            user.role = role
            user.save()
        else:
            user_m = Users()
            user_m.uphone = motherphone
            user_m.role = role
            user_m.save()

        # 保存数据到家长表
        parent = Parents()
        parent.uphone = motherphone
        parent.familyrole = 'mother'
        user1 = Users.objects.filter(uphone=motherphone).first()
        parent.user_id = user1.id  # 关联用户表
        parent.school_id = school.id  # 关联园所表
        parent.student_id = xuesheng.id  # 关联学生表
        parent.save()
    
    if leap2 == 1:
        user2 = Users.objects.filter(uphone=fatherphone).first()  # 查询用户表是否有该电话
        role = Role.objects.get(id=1)
        if user2:
            user2.role = role
            user2.save()
        else:
            user_f = Users()
            user_f.uphone = fatherphone
            user_f.role = role
            user_f.save()

        # 保存数据到家长表
        parent = Parents()
        parent.uphone = fatherphone
        parent.familyrole = 'father'
        user3 = Users.objects.filter(uphone=fatherphone).first()
        parent.user_id = user3.id  # 关联用户表
        parent.school_id = school.id  # 关联园所 id
        parent.student_id = xuesheng.id  # 关联学生表
        parent.save()

    if leap == 1:
        user4 = Users.objects.filter(uphone=grandpaphone).first()  # 查询用户表是否有该电话
        role = Role.objects.get(id=1)
        if user4:
            user4.role = role
            user4.save()
        else:
            user_g = Users()
            user_g.uphone = grandpaphone
            user_g.role = role
            user_g.save()

        # 保存数据到家长表
        parent = Parents()
        parent.uphone = grandpaphone
        parent.familyrole = 'grandpa'
        user5 = Users.objects.filter(uphone=grandpaphone).first()
        parent.user_id = user5.id  # 关联用户表
        parent.school_id = school.id  # 关联园所 id
        parent.student_id = xuesheng.id  # 关联学生表
        parent.save()
    return JsonResponse({'status': 'ok'})


# 学生测评详情
@csrf_exempt
def test_detail_views(request):
    sid = request.POST.get('sid')  # 获取学生id
    student = Student.objects.get(id=sid)
    upload_img(str(student.photo))  # 上传图片到七牛云
    url = download(str(student.photo))
    results = student.test_results.all().order_by('-yueling')  # 降序排序
    if results:
        count = len(results)  # 统计有多少份报告
        lst = []
        for result in results:
            tup = fx(int(result.yueling))  # 获取年龄，月龄（2,5）
            if type(tup) is tuple:
                title = '%d岁%d月龄测评报告%03d' % (tup[0], tup[1], count)
            else:
                title = '%d岁测评报告%03d' % (tup, count)
            dic = {
                'title': title,  # 报告名称
                'score': result.score,  # 分数
                'rid': result.id,  # 测试结果id
            }
            lst.append(dic)
            count -= 1
        dic_data = {
            'uname': student.uname,  # 姓名
            'age': fn(student.birth)[2],  # 月龄
            'gender': student.gender,  # 性别
            'photo': url,  # 学生头像
            'data': lst,  # 报告结果
        }
        return JsonResponse(dic_data)
    else:
        dic_data = {
            'uname': student.uname,  # 姓名
            'age': fn(student.birth)[2],  # 月龄
            'gender': student.gender,  # 性别
            'photo': url,  # 学生头像
        }
        return JsonResponse(dic_data)


# 开始测评页
@csrf_exempt
def start_test_views(request):
    sid = request.POST.get('sid')  # 获取学生id
    # 获取学生对象
    student = Student.objects.get(id=sid)
    # 获取园所
    school = student.school
    upload_img(str(school.logo))  # 上传图片到七牛云
    url = download(str(school.logo))
    birth = student.birth
    # 计算年龄，月份，总月龄
    yue_ling = fn(birth)  # (23, 11, 287) 23年龄，11月份，287总月龄
    dic = {
        'name': student.uname,
        'age': "%s岁%s个月" % (str(yue_ling[0]), str(yue_ling[1])),
        'gender': student.gender,
        'schoollogo': url,
        'introduce': school.introduce
    }
    return JsonResponse(dic)


# 测评题
@csrf_exempt
def exam_view(request):
    sid = request.POST.get('sid')  # 获取学生id
    student = Student.objects.get(id=sid)
    school = student.school  # 获取园所
    birth = student.birth
    moonage = fn(birth)
    if not Moonage.objects.filter(age=moonage[2]).exists():
        return JsonResponse({'status': 'failed', 'text': '没有该年龄的题'})
    powers = school.school_powers.all()

    l_powers = []
    for power in powers:
        # 获取月龄对应的能力线
        age = power.moonage_set.filter(age=moonage[2]).first()
        if age:
            # l_powers.append(power)
            l_powers.append(age)

    # 获取测评题目
    l_tests = []
    for capacity in l_powers:
        tests = capacity.tests.filter(isDelete=False).all()
        for k in tests:
            l_tests.append(k)

    # 添加题和选项
    l_choices = []
    for chose in l_tests:
        choices = chose.question_choices.all()  # 获取测评题选项
        lst_option = []  # 添加每题的所有选项
        for question in choices:
            dic = {
                'id': question.id,  # 选项id
                'optionname': question.choiceName,  # 选项名
            }
            lst_option.append(dic)
        dic1 = {
            'title': chose.biaoti,  # 题名
            'option': lst_option,  # 该题选项
        }
        l_choices.append(dic1)  # 加进列表中
    dic2 = {
         'count': len(l_choices),  # 题的数量
         'data': l_choices,  # 标题，选项数据
    }
    return JsonResponse(dic2)

# 测评结果
@csrf_exempt
def test_result_views(request):
    sid = request.POST.get('sid')  # 获取学生id
    student = Student.objects.get(id=sid)
    school = student.school  # 获取园所

    # 获取前端的选项 id
    ids = request.POST.get('ids')
    lst = json.loads(ids)

    birth = student.birth
    yue_ling = fn(birth)
    age = yue_ling[2]
    # 保存数据到Testresult
    testresutl = Testresutl()
    testresutl.yueling = age
    testresutl.xuesheng = student
    testresutl.save()

    # 园所对应能力线
    powers = school.school_powers.all()

    # 获取与月龄对应能力线的对象
    l_powers = []
    for power in powers:
        # 获取月龄对应的能力线
        moonage = power.moonage_set.filter(age=age).first()
        if moonage:
            # l_powers.append(power)
            l_powers.append(moonage)
    # 获取总分
    score = 0
    # 获取筛选出Test的数量
    i = 0
    # 获取测评结果Testresult对象
    obj = Testresutl.objects.filter(xuesheng_id=student.id, yueling=age).order_by('-id').first()
    for capacity in l_powers:
        # 保存数据到Testdetail中
        testdetail = Testdetail()

        able = capacity.abilities  # 月龄反向查找能力线
        testdetail.powername = able.powerTitle
        testdetail.testresult = obj
        testdetail.save()
        # tests = capacity.tests.all()  # 获取能力线题
        tests = capacity.tests.filter(isDelete=False).all()
        if not tests:
            return JsonResponse({'status': 'failed'})
        grade = 0  # 计算能力线结果
        for k in tests:
            i = i + 1
            choices = k.question_choices.all()  # 获取每道题选项
            for ch in choices:
                leap = 0
                # 获取每道题选项得分
                for id in lst:
                    if ch.id == int(id):
                        score = score + ch.grade
                        grade = grade + ch.grade

                        # 保存数据到 Questionresult表中
                        questionresult = Questionresult()
                        # 获取测评详情Testdetail对象
                        chr = Testdetail.objects.filter(testresult_id=obj.id, powername=capacity.abilities.powerTitle).first()
                        questionresult.questionName = k.biaoti
                        questionresult.getscore = ch.grade
                        questionresult.testdetail = chr
                        questionresult.save()
                        leap = 1
                        break
                if leap:
                    break
        grade = grade / len(tests)
        result = ''
        if grade > 0 and grade < 1.5:
            result = '劣'
        elif (grade > 1.5 or grade == 1.5) and grade < 2.5:
            result = '差'
        elif (grade > 2.5 or grade == 2.5) and grade < 3.5:
            result = '中'
        elif (grade > 3.5 or grade == 3.5) and grade < 4.5:
            result = '良'
        elif (grade > 4.5 or grade == 4.5) and (grade < 5 or grade == 5):
            result = '优'

        # 保存结果 到Testdetail中
        obj2 = Testdetail.objects.filter(powername=capacity.abilities.powerTitle, testresult_id=obj.id).first()
        obj2.result = result
        obj2.save()
    # 计算总分
    score = int((score / (i * 5)) * 100)
    # 保存到 Testresult 中
    obj.score = score
    obj.save()

    lst_powers = []
    # 筛选对应能力线结果
    testpowers = Testdetail.objects.filter(testresult_id=obj.id).all()
    for power_result in testpowers:
        dic = {
            'powername': power_result.powername,  # 能力线名
            'result': power_result.result,  # 结果
        }
        lst_powers.append(dic)

    upload_img(str(student.photo))  # 上传图片到七牛云
    url = download(str(student.photo))
    dic1 = {
        'name': student.uname,
        'photo': url,
        'age': age,
        'gender': student.gender,
        'score': score,
        'data': lst_powers
    }
    return JsonResponse(dic1)

